<?php


namespace app\service\user;


use app\model\partner\UserPartnerModel;
use app\model\user\PartnerMoneyRecordModel;
use app\service\BaseService;

class PartnerMoneyRecordService extends BaseService
{

    public function __construct()
    {
        $this->model = new PartnerMoneyRecordModel();
    }

    const ORDER = 1;
    const WITHDRAW_BACK = 2;
    const VERIFY_CART = 3;
    const INVITE_USER_BUY = 4;

    const WITHDRAW = 101;


    protected $typeArr = [
        // 余额增加
        self::ORDER => '课时工资',
        self::WITHDRAW_BACK => '提现失败退回',
        self::VERIFY_CART => '验车工资',
        self::INVITE_USER_BUY => '成功邀请好友%s下单',

        self::WITHDRAW => '提现',
    ];


    public function getTypeArr()
    {
        return $this->typeArr;
    }

    public function getTypeText($key)
    {
        $arr = $this->typeArr;
        return isset($arr[$key]) ? $arr[$key] : '未知类型';
    }

    public function createLog($title, $userId, $type, $amount, $relatedUid, $orderSn, $remark = '')
    {
        $userInfo = UserPartnerModel::lock('lock in share mode')->where('id', $userId)->find();
        if (!$userInfo) {
            return true;
        }
        $before = $userInfo['money'];
        $after = $type > 100 ? bcsub($before, $amount, 2) : bcadd($before, $amount, 2);
        if (in_array($type, [1, 3, 4])) {
            $userInfo->income_amount = $userInfo['income_amount'] + $amount;
        }
        $userInfo->money = $after;
        $userInfo->save();

        $model = $this->model;
        $model->title = $title;
        $model->user_id = $userId;
        $model->type = $type;
        $model->before = $before;
        $model->amount = $amount;
        $model->after = $after;
        $model->related_uid = $relatedUid;
        $model->order_sn = $orderSn;
        $model->remark = $remark;
        $model->save();
        return true;
    }
}